<!--
 * @Author: June
 * @Date: 2022-11-15 10:13:24
 * @LastEditors: 无处安放的六月
 * @LastEditTime: 2023-12-05 16:25:18
 * @Description:  系统字段配置
 *
-->
<template>
  <div class="app-container">
    <el-row class="cardBox">
      <leftTree ref="leftTree" :data="treeData" node-key="code" :default-props="defaultProps" search-key="name" width="300px" :default-expand-keys="defaultExpandKeys"  @handleNodeClickAll="handleNodeClick" />
        <el-col id="right-content" class="right-content" :offset="0" :span="18">
          <div class="box-title">
            <el-breadcrumb separator="/" style="line-height:50px;">
              <el-breadcrumb-item v-for="(item,index) in breadcrumb" :key="index">{{ item }}</el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          <div class="box-card">
          <el-alert title="双击想要修改的字段进行修改。" type="info" show-icon :closable="false" />
          <el-table v-if="showTable" ref="tableData" v-loading="loading" :data="tableData" stripe border @cell-dblclick="tableDbEdit">
            <el-table-column type="selection" align="center"></el-table-column>
            <el-table-column align="center" type="index" label="索引" width="60px" />
            <el-table-column align="center" prop="id" label="主键" width="140px" />
            <el-table-column align="center" prop="val" label="字段名称">
              <template slot="header">
                字段名称
                <i class="el-icon-edit" :style="{ color: themeColor }" />
              </template>
            </el-table-column>
            <el-table-column align="center" prop="code" label="字段编码" show-overflow-tooltip min-width="150px" />
            <el-table-column align="center" prop="remark" label="字段描述">
              <template slot="header">
                字段描述
                <i class="el-icon-edit" :style="{ color: themeColor }" />
              </template>
            </el-table-column>
            <el-table-column align="center" prop="width" label="字段宽度">
              <template slot="header">
                字段长度(px)
                <i class="el-icon-edit" :style="{ color: themeColor }" />
              </template>
              <template slot-scope="scope">{{ scope.row.width }}</template>
            </el-table-column>
            <el-table-column align="center" prop="sort" label="字段排序">
              <template slot="header">
                字段排序
                <i class="el-icon-edit" :style="{ color: themeColor }" />
              </template>
            </el-table-column>
            <el-table-column align="center" prop="align" label="对齐方式">
              <template slot="header">
                对齐方式
                <i class="el-icon-edit" :style="{ color: themeColor }" />
              </template>
              <template scope="scope">
                <el-select v-model="scope.row.align" @change="submit(scope.row)">
                  <el-option value="left" label="靠左">靠左</el-option>
                  <el-option value="center" label="居中">居中</el-option>
                  <el-option value="right" label="靠右">靠右</el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="status" label="是否启用">
              <template #default="{ row }">
                <el-switch v-model="row.status" :active-value="1" :inactive-value="0" @change="submit(row)" />
              </template>
            </el-table-column>
          </el-table>
          </div>
          <el-row>
            <div class="table-btn-box">
              <el-button
                  @click="() => {
                    tableData.forEach(row => {
                      $refs['tableData'].toggleRowSelection(row, true)
                    })
                  }
                ">选择全部</el-button>
              <el-button
                  @click="() => {
                    tableData.forEach(row => {
                      $refs['tableData'].toggleRowSelection(row)
                    })
                  }
                ">反向选择</el-button>
              <el-button>
                更多操作
                <i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
            </div>
          </el-row>
      </el-col>
    </el-row>
        <!-- <div class="box-card">
          <el-input v-model.trim="filterText" prefix-icon="el-icon-search" placeholder="输入关键字进行过滤" />
          <el-tree ref="tree" node-key="label" accordion :expand-on-click-node="false" :filter-node-method="filterNode" :data="treeData" highlight-current :default-expanded-keys="defaultExpandKeys" :props="defaultProps" @node-click="handleNodeClick" />
        </div> -->

  </div>
</template>
<script>
import leftTree from '@/components/LeftTree'
import { mapGetters } from 'vuex'

export default {
  components: { leftTree },
  data() {
    return {
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      defaultExpandKeys: ['A', 'A-1', 'A-1-1'],
      tableData: [],
      filterText: '',
      breadcrumb: ['基础信息', '系统设置', '人员管理'],
      loading: false,
      showTable: true,
      route: '/basicInfo/sys/user'
    }
  },
  computed: {
    ...mapGetters(['themeColor'])
  },
  created() {},
  mounted() {
    this.getTreeData()
    this.getField()
  },
  methods: {
    /**
     * @description: 获取所有字段
     * @return {*}
     */
    async getField() {
      this.loading = true
      this.showTable = false
      const res = await this.$axios.get(
        `/platform/field/listPlatform?route=${this.route}`
      )
      if (res?.data.code === 200) {
        this.showTable = true
        this.tableData = res.data.data
        setTimeout(() => {
          this.loading = false
        }, 10)
      }
    },
    /**
     * @description: 处理菜单数据
     * @return {*}
     */
    getTreeData() {
      // 不需要展示的菜单或模块  路由的name
      const badList = ['Dashboard', 'Board', '初始化信息', '数据看板']
      const list = JSON.parse(
        JSON.stringify(
          JSON.parse(sessionStorage.getItem('FIVE_MENU_LIST')).filter(
            (item) =>
              item.type === 1 &&
              item.children &&
              !badList.includes(item.name || item.meta.title)
          )
        )
      )
      const newList = this.setTitle(list.map(item => {
        !item.url && (item.url = item.path)
        return item
      }))
      this.treeData = newList
      this.$nextTick(() => {
        this.$refs['leftTree']?.$refs['tree']?.setCurrentKey('A-1-1')
      })
    },
    /**
     * @description: 处理数据 名称
     * @param {*} data
     * @return {*}
     */
    setTitle(data) {
      data.forEach((item) => {
        if (item.children && item.children.length) {
          item.children.forEach((el) => {
            el.url = item.url + '/' + el.path
          })
          this.setTitle(item.children)
        }
      })
      return data
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    /**
     * @description: 树节点点击
     * @param {*} data
     * @param {*} node
     * @return {*}
     */
    handleNodeClick({ data, node }) {
      console.log(node)
      if (data.children && data.children.length) {
        return
      } else {
        this.breadcrumb = []
        this.returnNodeLabel(node.parent)
        this.breadcrumb.push(data.label)
        this.route = data.url
        this.getField()
      }
    },
    /**
     * @description: 递归获取名称
     * @param {*} node
     * @return {*}
     */
    returnNodeLabel(node) {
      if (node.parent) {
        this.breadcrumb.unshift(node.data.label)
        this.returnNodeLabel(node.parent)
      }
    },
    /**
     * @description:  双击表格编辑
     * @param {*} row
     * @param {*} column
     * @param {*} cell
     * @param {*} event
     * @return {*}
     */
    tableDbEdit(row, column, cell, event) {
      console.log(row, column)
      if (['val', 'remark', 'width', 'sort'].includes(column.property)) {
        var beforeVal = event.target.textContent
        event.target.innerHTML = ''
        let type = 'text'
        if (['width', 'sort'].includes(column.property)) {
          type = 'number'
          beforeVal = Math.abs(Number(beforeVal))
        }
        const str = `<div class='cell'>
            <div class='el-input el-input--mini'>
              <input type=${type} placeholder='请输入内容' class='el-input__inner' maxlength="20">
            </div>
        </div>`
        cell.innerHTML = str
        const cellInput = cell.children[0].children[0].children[0]
        cellInput.value = beforeVal
        cellInput.focus()
        cellInput.onblur = () => {
          const onblurCont = `<div class='cell'>${cellInput.value}</div>`
          cell.innerHTML = onblurCont
          row[column.property] = cellInput.value.replace(/ /g, '')
          if (beforeVal !== cellInput.value) {
            // 调用接口修改
            this.submit(row)
          }
        }
      } else {
        this.$notify.error(`${column.label}不支持修改！`)
      }
    },
    /**
     * @description: 字段修改
     * @param {*} row
     * @return {*}
     */
    async submit(row) {
      const { code, val, width, status, sort, remark, route, align } = row
      const res = await this.$axios.post('/platform/field/update', {
        code,
        val,
        width,
        status,
        sort,
        remark,
        route,
        align
      })
      if (res?.data.code === 200) {
        this.$notify.success('修改成功！')
        this.loading = false
        this.getField()
      } else {
        this.loading = false
        this.$notify.error('修改失败！')
      }
    }
  }
}
</script>
<style lang='scss' scoped>
.app-container {
  display: 100%;
    .box-card {
      .el-breadcrumb {
        // background-color: #edf6ff;
        padding: 10px;
        border-radius: 5px;
        margin-bottom: 10px;
      }
      .el-alert {
        margin: 10px 0;
        width: 270px;
        padding: 5px 20px;
      }
      .el-icon-edit {
        font-weight: bold;
        font-size: 14px;
      }
    }
}
</style>
